package com.example.demo.project.sys;



import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 系统变量
 */
public enum SysVariable {
	
	INSTANCE;
	
	private Properties props;
	private final Map<String, String> cache = new HashMap<>();

	public synchronized void setProps(Properties props) {
		this.props = props;
		cache.clear();
	}

	private Pattern p =  Pattern.compile("\\$\\{(.+?)\\}");

	/**
	 * 获取配置文件值的方法
	 * @param key
	 * @return
	 */
	private String getValue(String key) {
		/**
		 * 获取计算过的值
		 */
		final String cacheValue = cache.get(key);
		if (null != cacheValue) return cacheValue;

		/**
		 * 获取未计算的值
		 */
		final String propValue = props.getProperty(key);
		if (null == propValue) return propValue;

		/**
		 * 计算值
		 */
		StringBuffer calValBuffer = new StringBuffer();
		final Matcher matcher = p.matcher(propValue);
		while(matcher.find()) {
			String subVal = getValue(matcher.group(1));
			if (null == subVal) throw new IllegalStateException(String.format("\"%s\"取值失败，不存在变量配置\"%s\"。", key, matcher.group()));
			matcher.appendReplacement(calValBuffer, subVal);
		}
		matcher.appendTail(calValBuffer);

		/**
		 * 缓存计算的值
		 */
		final String calVal = calValBuffer.toString();
		cache.put(key, calVal);

		return calVal;
	}

	/**
	 * 获取配置值的静态方法
	 * @param key
	 * @return
	 */
	public static String get(String key) {
		/*if (key.equals("CostCloudAPI")) {
			return "http://192.168.0.102:8081/webapi/ecms";
		}*/
		String val = SysVariable.INSTANCE.getValue(key);
//		if (null == val) throw new IllegalStateException("没有找到系统变量【" + key + "】的配置");
		return val;
	}

	public static boolean getBoolean(String key) {
		String str = SysVariable.INSTANCE.getValue(key);
		return Boolean.valueOf(str);
	}

	public Set<Object> keySet() {
		return (null != props) ? props.keySet() : Collections.emptySet();
	}

	/**
	 * 更新值
	 * @param key
	 * @param value
	 */
	public void update(String key, String value, boolean effectImmediately) {
		props.put(key, value);
		if (effectImmediately) {
			cache.remove(key);
		}
	}
}
